package logic

import (
	"ball/cache"
	"ball/pkg"
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"ball/ballrpc/ballrpc"
	"ball/ballrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信验证
func (l *SendSmsLogic) SendSms(in *ballrpc.SendSmsRequest) (*ballrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "xianzhi"+in.Tel).Result()
	if result >= "1" {
		return nil, fmt.Errorf("每分钟只能发一次")
	}
	code := rand.Intn(9000) + 1000
	send, err := pkg.Send(in.Tel, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *send.Body.Code != "OK" {
		return nil, fmt.Errorf(*send.Body.Message)
	}
	cache.Rdb.Set(l.ctx, "SendSms"+in.Tel, code, time.Hour*3)

	cache.Rdb.Incr(l.ctx, "xianzhi"+in.Tel)

	cache.Rdb.Expire(l.ctx, "xianzhi"+in.Tel, time.Minute*1)
	return &ballrpc.SendSmsResponse{}, nil
}
